package _11反射获取成员变量Field;

import com.asin.domain.Person;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class DemoGetField {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class<Person> personClass = Person.class;

        //获取所有权限的成员变量。不包括继承
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            System.out.println(name);
        }
        System.out.println("=============================");

        //获取public权限的成员变量。包括继承父类的
        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        System.out.println("=============================");

        //利用反射为成员变量赋值
        Field field = personClass.getDeclaredField("name");
        field.setAccessible(true);
        Person p = new Person();
        field.set(p,"张三");
        System.out.println("p = " + p);
        System.out.println("=============================");

        //利用反射获得成员变量的值
        Object o = field.get(p);
        System.out.println(o);


    }
}
